package com.hy.admin.service.impl;

import java.util.*;

import com.hy.admin.dao.*;
import com.hy.admin.entity.*;
import com.hy.admin.enums.*;
import com.hy.admin.service.MessageService;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hy.admin.helper.response.QuestionResponse;
import com.hy.admin.service.QuestionService;
import com.hy.core.response.ServicesResult;
import com.hy.utils.CommonUtility;
import com.hy.utils.OSSUtil;

@Service
public class QuestionServiceImpl implements QuestionService {

    @Autowired
    private QuestionDao questionDao;
    @Autowired
    private ImageDao imageDao;
    @Autowired
    private MemberPayQuestionDao memberPayQuestionDao;
    @Autowired
    private QuestionLikeDao questionLikeDao;
    @Autowired
    private MemberDao memberDao;
    @Autowired
    private MessageService messageService;

    @Override
    public ServicesResult<List<MemberQuestionEntity>> listByMemberId(Long memberId, Integer queState, Integer pageNum, Integer pageSize) {
        ServicesResult<List<MemberQuestionEntity>> servicesResult = new ServicesResult<>();
        //校验请求参数
        if (memberId == null || memberId < 0){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请求报文有误");
            return servicesResult;
        }
        //设置分页条件，Parameters:pageNum 页码pageSize 每页显示数量count 是否进行count查询
        if(pageNum == null || pageNum <= 0){
            //初始页码为1
            pageNum = 1;
        }
        if(pageSize == null || pageSize <= 0){
            //初始数量为20
            pageSize = 20;
        }
        PageHelper.startPage(pageNum, pageSize);
        //查询用户的所有问题
        List<MemberQuestionEntity> questionList = questionDao.selectByMemberId(memberId, EnumImageRelatedType.HEAD_IMAGE.getId(), queState);
        servicesResult.setResult(questionList);
        return servicesResult;
    }

    @Override
    public ServicesResult<List<MemberQuestionEntity>> listByTeacherId(Long teacherId, Integer queState, Integer pageNum, Integer pageSize) {
        ServicesResult<List<MemberQuestionEntity>> servicesResult = new ServicesResult<>();
        //校验请求参数
        if (teacherId == null || teacherId < 0){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请求报文有误");
            return servicesResult;
        }
        //设置分页条件，Parameters:pageNum 页码pageSize 每页显示数量count 是否进行count查询
        if(pageNum == null || pageNum <= 0){
            //初始页码为1
            pageNum = 1;
        }
        if(pageSize == null || pageSize <= 0){
            //初始数量为20
            pageSize = 20;
        }
        PageHelper.startPage(pageNum, pageSize);
        //查询教师的所有问题
        List<MemberQuestionEntity> questionList = questionDao.selectByTeacherId(teacherId, EnumImageRelatedType.HEAD_IMAGE.getId(), queState);
        servicesResult.setResult(questionList);
        return servicesResult;
    }

    @Override
    public ServicesResult<List<MemberQuestionEntity>> listByIsChoice(Integer pageNum, Integer pageSize) {
        ServicesResult<List<MemberQuestionEntity>> servicesResult = new ServicesResult<>();
        //设置分页条件，Parameters:pageNum 页码pageSize 每页显示数量count 是否进行count查询
        if(pageNum == null || pageNum <= 0){
            //初始页码为1
            pageNum = 1;
        }
        if(pageSize == null || pageSize <= 0){
            //初始数量为20
            pageSize = 20;
        }
        PageHelper.startPage(pageNum, pageSize);
        //查询教师的所有问题
        List<MemberQuestionEntity> questionList = questionDao.selectByIsChoice(EnumImageRelatedType.HEAD_IMAGE.getId(), EnumIsChoice.YES.getId());
        servicesResult.setResult(questionList);
        return servicesResult;
    }

    @Override
    public ServicesResult<Boolean> updateChoice(Long id, Integer isChoice) {
        ServicesResult<Boolean> servicesResult = new ServicesResult<>();
        servicesResult.setResult(false);
        //校验请求参数
        if (id <= 0){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请求报文有误");
            return servicesResult;
        }
        QuestionEntity question = questionDao.selectByPrimaryKey(id);
        if(question == null){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("该问题不存在");
            return servicesResult;
        }
        if(question.getIsPublic() == EnumIsPublic.NO.getId()){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请选择公开问题");
            return servicesResult;
        }
        if(question.getIsChoice() == isChoice){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请勿重复设置");
            return servicesResult;
        }
        int count = questionDao.updateChoice(id, isChoice);
        if(count <= 0){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("操作失败");
            return servicesResult;
        }
        servicesResult.setResult(true);
        return servicesResult;
    }

    @Override
    public ServicesResult<List<MemberQuestionEntity>> listByTeacherIdAndIsPublic(Long teacherId, Integer pageNum, Integer pageSize) {
        ServicesResult<List<MemberQuestionEntity>> servicesResult = new ServicesResult<>();
        //设置分页条件，Parameters:pageNum 页码pageSize 每页显示数量count 是否进行count查询
        if(pageNum == null || pageNum <= 0){
            //初始页码为1
            pageNum = 1;
        }
        if(pageSize == null || pageSize <= 0){
            //初始数量为20
            pageSize = 20;
        }
        PageHelper.startPage(pageNum, pageSize);
        //查询教师的所有问题
        List<MemberQuestionEntity> questionList = questionDao.selectByTeacherAnswered(
                teacherId,EnumImageRelatedType.HEAD_IMAGE.getId(), EnumIsPublic.YES.getId(),EnumQuestionState.ANSWER.getId());
        servicesResult.setResult(questionList);
        return servicesResult;
    }

    @Override
    public ServicesResult<QuestionResponse> detail(Long memberId, Long id) {
        ServicesResult<QuestionResponse> servicesResult = new ServicesResult<>();
        //校验请求参数
        if (id == null || id < 0){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请求报文有误");
            return servicesResult;
        }
        //查询问题详情
        QuestionEntity questionEntity = questionDao.selectByPrimaryKey(id);
        //查询问题关联图片
        //List<String> imageList = imageDao.selectByRelatedIdAndType(questionEntity.getId(), EnumImageRelatedType.QUESTION.getId());


        //处理返回数据
        QuestionResponse questionResponse = new QuestionResponse();
        questionResponse.setQuestion(questionEntity);
        if(memberId != null && memberId > 0) {
            //查询用户是否购买该问题答案
            int count = memberPayQuestionDao.selectByMIdAndQId(memberId, id);
            questionResponse.setIsPay(count>0 ? true : false);
        }
//        if(imageList != null && imageList.size()>0){
//            questionResponse.setImageList(imageList);
//        }

        servicesResult.setResult(questionResponse);
        return servicesResult;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public ServicesResult<Boolean> add(QuestionEntity questionEntity, MultipartFile[] files) throws Exception {
        ServicesResult<Boolean> servicesResult = new ServicesResult<>();
        //校验请求参数
        if (questionEntity == null){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请求报文有误");
            return servicesResult;
        }
        //校验必传参数
        if (questionEntity.getMemberId() == null){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请求参数有误，必传参数为空");
            return servicesResult;
        }
//        if (questionEntity.getTeacherId() == null){
//            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
//            servicesResult.setStatusMsg("请求参数有误，必传参数为空");
//            return servicesResult;
//        }
//        if (StringUtils.isEmpty(questionEntity.getTitle())){
//            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
//            servicesResult.setStatusMsg("请求参数有误，必传参数为空");
//            return servicesResult;
//        }
        if (StringUtils.isEmpty(questionEntity.getDescr())){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请求参数有误，必传参数为空");
            return servicesResult;
        }
        if (questionEntity.getIsPublic() == null){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请求参数有误，必传参数为空");
            return servicesResult;
        }
        List<String> imageUrlList = new ArrayList<>();
        if(files!=null && files.length>0) {
            //上传图片至阿里云OSS
            boolean result = true;
            for (MultipartFile file : files) {
                //获取文件名
                String fileName = file.getOriginalFilename();
                String fileType = fileName.substring(fileName.indexOf(".") + 1, fileName.length());
                //使用工具类
                String imagePath = OSSUtil.uploadFile(CommonUtility.multipartToFile(file), fileType);
                if (imagePath == null || StringUtils.isEmpty(imagePath)) {
                    result = false;
                    break;
                }
                imageUrlList.add(imagePath);
            }


            if (imageUrlList == null) {
                //第一个文件上传失败
                servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
                servicesResult.setStatusMsg("文件上传oss失败");
                return servicesResult;
            }
            if (!result) {//部分图片上传成功
                //图片上传失败---删除上传成功的图片
                OSSUtil.deleteFiles(imageUrlList);
                //删除图片失败---不做处理，每次上传的文件名根据uuid重新生成，对上传失败的文件没有影响
                servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
                servicesResult.setStatusMsg("文件上传oss失败");
                return servicesResult;
            }
        }
        //存入数据库
        String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
        questionEntity.setUuid(uuid);
        questionEntity.setQueState(EnumQuestionState.ASK.getId());
        questionEntity.setIsChoice(EnumIsChoice.NO.getId());
        if (questionEntity.getTeacherId() == null){
            questionEntity.setIsPlatform(EnumIsPlatform.YES.getId());
        }

        Calendar cal = Calendar.getInstance();

        questionEntity.setCreateTime(cal.getTime());
        questionEntity.setUpdateTime(cal.getTime());
        questionEntity.setStatus(EnumStatus.VALID.getId());
        int count = questionDao.insertSelective(questionEntity);
        if(count <= 0 && imageUrlList.size()>0){
            //提问数据插入失败
            //删除上传的图片
            OSSUtil.deleteFiles(imageUrlList);
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("数据库插入失败");
            return servicesResult;
        }
        if(imageUrlList.size()>0) {
            //根据uuid查询问题数据，与图片表做关联
            questionEntity = questionDao.selectByUuid(uuid);
            List<ImageEntity> imageList = new ArrayList<>();
            for (String imageUrl : imageUrlList) {
                ImageEntity image = new ImageEntity();
                image.setImgPath(imageUrl);
                image.setRelatedId(questionEntity.getId());
                image.setRelatedType(EnumImageRelatedType.QUESTION.getId());
                image.setCreateTime(cal.getTime());
                image.setUpdateTime(cal.getTime());
                image.setStatus(EnumStatus.VALID.getId());
                image.setIsDelete(EnumIsDelete.NO.getId());
                imageList.add(image);
            }
            count = imageDao.batchInsert(imageList);
            if (count != imageList.size()) {
                //删除已上传图片
                OSSUtil.deleteFiles(imageUrlList);
                //插入失败，启动事务回滚
                throw new Exception("插入图片失败");
            }
        }
        //推送给教师
        if (questionEntity.getTeacherId() != null && questionEntity.getTeacherId() > 0) {
            MemberEntity member = memberDao.selectById(questionEntity.getTeacherId());
            if (member != null && StringUtils.isNotBlank(member.getDeviceToken())) {
                messageService.addMessageForOne(member.getId(), member.getDeviceToken(), member.getAliDeviceId(), "有家长向您提出新的提问，请注意查看！","您有新的提问");
            }
        }
        servicesResult.setResult(true);
        return servicesResult;
    }

    @Override
    public PageInfo<MemberQuestionEntity> listByTeacherId(Long teacherId, Integer pageNum, Integer pageSize) {
    	//校验请求参数
    	if (teacherId == null || teacherId < 0){
    		return null;
    	}
    	//设置分页条件，Parameters:pageNum 页码pageSize 每页显示数量count 是否进行count查询
    	if(pageNum == null || pageNum <= 0){
    		//初始页码为1
    		pageNum = 1;
    	}
    	if(pageSize == null || pageSize <= 0){
    		//初始数量为20
    		pageSize = 20;
    	}
    	Page<MemberQuestionEntity> page = PageHelper.startPage(pageNum, pageSize, true);
    	//查询教师的所有问题
    	questionDao.selectByTeacherIdAndIsPublic(teacherId, 
    			EnumImageRelatedType.HEAD_IMAGE.getId(), 
    			EnumIsPublic.YES.getId(), null);
    	
    	PageInfo<MemberQuestionEntity> pageInfo = page.toPageInfo();
    	return pageInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ServicesResult<Boolean> like(Long questionId, Long memberId) throws Exception {
        ServicesResult<Boolean> servicesResult = new ServicesResult<>();
        //校验请求参数
        if (questionId == null || questionId <= 0){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请求报文有误");
            return servicesResult;
        }

        //校验请求参数
        if (memberId == null || memberId <= 0){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请求报文有误");
            return servicesResult;
        }

        int count = questionLikeDao.selectCountByQIdAndMId(questionId, memberId);
        if(count > 0){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请勿重复点赞");
            return servicesResult;
        }
        QuestionLikeEntity questionLike = new QuestionLikeEntity();
        questionLike.setMemberId(memberId);
        questionLike.setQuestionId(questionId);
        questionLike.setCreateTime(new Date());
        questionLike.setStatus(EnumStatus.VALID.getId());
        count = questionLikeDao.insertSelective(questionLike);
        if(count <= 0){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("点赞失败");
            return servicesResult;
        }
        count = questionDao.updateLikeNum(questionId);
        if(count <= 0){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("点赞失败");
            throw new Exception("点赞失败");
        }
        servicesResult.setResult(count > 0);
        return servicesResult;
    }
}
